//
//  LeftSideViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/20.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SVProgressHUD
import SwiftyJSON

class LeftSideViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,LeftCollectionViewCellDelegate {
    
    
    var myTableView = UITableView(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH*0.25, height: SCREEN_HEIGHT-64), style: .plain)
    var myScrollView = UIScrollView()
    var myCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout())
    
    var tableDataArray = NSMutableArray()
    var scrollDataArray = NSMutableArray()
    var dataArray = NSMutableArray()
    
    var buttonsArray = NSMutableArray()
    var customScrView = UIView()
    var agoButton : UIButton?
    
    var tableViewIndex = 0
    var buttonIndex = 0
    var collectionViewIndex = 0
    
    
    
    
    let TABLEVIEWCELL = "myTableViewCell"
    let COLLECTIONVIEWCELL = "mycollectionVIEWCELL"
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.automaticallyAdjustsScrollViewInsets = false
        self.creatNavVIew()
        
        self.getData()
        self.creatTableView()
        self.creatScrollView()
        self.creatCollectionView()
        
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        sideMenuViewController()?.menuContainerView?.allowPanGesture = false
    }
    
}


extension LeftSideViewController{
    
    fileprivate func creatNavVIew(){
        
        self.title = "Category"
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
    }
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
}

extension LeftSideViewController{
    fileprivate func getData(){
        let parma = ["main_page":"category","cPath":"all"]
        NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: parma as [String : NSObject]) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                let dataArr = (result as? NSDictionary)!["data"]as?[[String:NSObject]]
                for bigDic in dataArr!{
                    self.tableDataArray.add((bigDic["categories_name"]as?String)!)
                    let myMinArr = NSMutableArray()
                    let childArr = bigDic["child"]as?[[String:NSObject]]
                    for smallDic in childArr!{
                        let mySmallArr = NSMutableArray()
                        self.scrollDataArray.add((smallDic["categories_name"]as?String)!)
                        let minChildArr = smallDic["child"]as?[[String:NSObject]]
                        for minDic in minChildArr!{
                            let model = LeftModel(dictionary: minDic as NSDictionary)
                            mySmallArr.add(model)
                        }
                        myMinArr.add(mySmallArr)
                    }
                    self.dataArray.add(myMinArr)
                }
                self.creatBtn()
                self.myTableView.reloadData()
                self.myCollectionView.reloadData()
                
            }else{
                SVProgressHUD.showError(withStatus: "get leftData error:" + String(describing: error))
                print("get leftData error:" + String(describing: error))
            }
        }
        
    }
    
    
}
extension LeftSideViewController{
    fileprivate func creatTableView(){
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.rowHeight = SCREEN_HEIGHT*0.1
        myTableView.backgroundColor = UIColor(red: 70/255.0, green: 180/255.0, blue: 250/255.0, alpha: 1)
        myTableView.separatorStyle = .none
        self.view.addSubview(myTableView)
        
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableDataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: TABLEVIEWCELL)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: TABLEVIEWCELL)
        }
        
        if SCREEN_WIDTH == 320 {
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 10)
        }else{
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 12)
        }
        cell?.backgroundColor = UIColor(red: 70/255.0, green: 180/255.0, blue: 250/255.0, alpha: 1)
        cell?.textLabel?.text = self.tableDataArray[indexPath.row] as? String
        
        let indexPath = IndexPath(row: 0, section: 0)
        
        myTableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_HEIGHT*0.06
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableViewIndex = indexPath.row
        self.myCollectionView.reloadData()
    }
    
    
}

extension LeftSideViewController{
    fileprivate func creatScrollView(){
        myScrollView.frame = CGRect(x: SCREEN_WIDTH*0.25, y: 64, width: SCREEN_WIDTH*0.75, height: SCREEN_HEIGHT*0.05)
        myScrollView.backgroundColor = UIColor.white
        self.view.addSubview(myScrollView)
        
        customScrView.frame = CGRect( x: 0, y: SCREEN_HEIGHT*0.05-2, width: SCREEN_WIDTH*0.75/3, height: 2)
        customScrView.backgroundColor = UIColor.red
        myScrollView.addSubview(customScrView)
    }
    
    func creatBtn(){
        
        for i in 0..<self.scrollDataArray.count {
            let button = UIButton(type: .custom)
            button.frame = CGRect(x: CGFloat(i)*SCREEN_WIDTH*0.75/3, y: 0, width: SCREEN_WIDTH*0.75/3, height: SCREEN_HEIGHT*0.05-2)
            button.setTitle(self.scrollDataArray[i] as? String, for: UIControlState())
            button.addTarget(self, action: #selector(scrollBtnClick(_:)), for: .touchUpInside)
            button.setTitleColor(UIColor.black, for: UIControlState())
            button.setTitleColor(UIColor.red, for: .selected)
            button.tag = i
            buttonsArray.add(button)
            if i == 0 {
                button.isSelected = true
                agoButton = button
            }else{
                button.isSelected = false
            }
            myScrollView.addSubview(button)
            
        }
    }
    
    func scrollBtnClick(_ button:UIButton){
        agoButton?.isSelected = false
        button.isSelected = true
        agoButton = button
        
        buttonIndex = button.tag
        
        UIView.animate(withDuration: 0.3, animations: { 
            self.customScrView.frame = CGRect(x: SCREEN_WIDTH*0.75/3*CGFloat(button.tag), y: SCREEN_HEIGHT*0.05-2, width: SCREEN_WIDTH*0.75/3, height: 2)
        }) 
        
        let indexPath = IndexPath(item: button.tag, section: 0)
        
        myCollectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: false)
        myCollectionView.reloadData()
    }
}


extension LeftSideViewController{
    fileprivate func creatCollectionView(){
        let layout  = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: SCREEN_WIDTH*0.75, height: SCREEN_HEIGHT*0.95-64)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
        layout.scrollDirection = .horizontal
        
        myCollectionView.frame = CGRect(x: SCREEN_WIDTH*0.25, y: SCREEN_HEIGHT*0.05+64, width: SCREEN_WIDTH*0.75, height: SCREEN_HEIGHT*0.95-64)
        myCollectionView.collectionViewLayout = layout
        myCollectionView.backgroundColor = UIColor.white
        myCollectionView.isPagingEnabled = true
        myCollectionView.delegate = self
        myCollectionView.dataSource = self
        myCollectionView.showsHorizontalScrollIndicator = false
        myCollectionView.showsVerticalScrollIndicator = false
        myCollectionView.bounces = false
        myCollectionView.alwaysBounceHorizontal = true
        self.view.addSubview(myCollectionView)
        myCollectionView.register(LeftCollectionViewCell.self, forCellWithReuseIdentifier: COLLECTIONVIEWCELL)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return dataArray.count-1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: COLLECTIONVIEWCELL, for: indexPath)
        (cell as? LeftCollectionViewCell)?.delegate = self
        if tableViewIndex == 2  {
            if buttonIndex == 0 {
                (cell as? LeftCollectionViewCell)?.dataArray = []
            }else{
                (cell as? LeftCollectionViewCell)?.dataArray = (dataArray[tableViewIndex] as? NSArray)![buttonIndex-1] as? NSArray
            }
            
        }else{
            (cell as? LeftCollectionViewCell)?.dataArray = (dataArray[tableViewIndex] as? NSArray)![buttonIndex] as? NSArray
        }
        
        return cell
        
    }
    
    func letSelfGotoProductVCWithStr(_ id: String, name: String) {
        let productVC = ProductListViewController()
        productVC.cPathStr = id
        productVC.title = name
        productVC.categories_name = name
        self.navigationController?.pushViewController(productVC, animated: true)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == myCollectionView {
            
            let index = Int(scrollView.contentOffset.x/(SCREEN_WIDTH*0.75))
            buttonIndex = index
            let button = buttonsArray[index] as? UIButton
            agoButton?.isSelected = false
            button!.isSelected = true
            agoButton = button
            
            
            
            UIView.animate(withDuration: 0.3, animations: {
                self.customScrView.frame = CGRect(x: SCREEN_WIDTH*0.75/3*CGFloat(button!.tag), y: SCREEN_HEIGHT*0.05-2, width: SCREEN_WIDTH*0.75/3, height: 2)
            }) 
            
            myCollectionView.reloadData()

        }
        
    }
    
}


















